package xyz.cerberu.cet.global.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author β世界
 * Created on 11:10
 * @Description 异步方法执行配置
 */
@Configuration
@EnableAsync
public class TaskConfig {

    /**
     * @author β世界 on 17:43 2021/3/12
     * 配置异步方法的执行线程池
     * @return org.springframework.core.task.TaskExecutor
     **/
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(15);
        // 队列的最大容量
        executor.setQueueCapacity(30);
        // 设置当处理队列到满的时候，如何处理新的任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池内容
        executor.initialize();
        return executor;
    }

}
